package cms

import (
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"os"
	"path"
	"wave-admin/global"
	"wave-admin/model/cms"
	"wave-admin/model/cms/request"

	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gopkg.in/yaml.v2"
)

type BlogService struct{}

func (blogService *BlogService) BlogConfig() (config *cms.BlogConfig, err error) {
	if global.GnConfig.System.BlogGeneration {
		workDir, _ := os.Getwd()
		v := viper.New()
		v.SetConfigName("config")
		v.SetConfigType("yaml")
		v.AddConfigPath(workDir + "/../../" + global.GnConfig.System.BlogDir)
		err := v.ReadInConfig()
		if err != nil {
			return config, err
		}
		v.WatchConfig()

		if err := v.Unmarshal(&config); err != nil {
			fmt.Println(err)
			return config, err
		}
		return config, err

	} else {
		return config, errors.New("未开启一键生成博客")
	}
}

func (blogService *BlogService) BlogConfigSave(req request.ReqConfig) (err error) {
	workDir, _ := os.Getwd()
	filePath := workDir + "/../../" + global.GnConfig.System.BlogDir + "/config.yaml"
	if config, err := blogService.BlogConfig(); err != nil {
		return err
	} else {
		config.BaseURL = req.BaseURL
		config.Title = req.Title
		config.Theme = req.Theme
		config.DefaultContentLanguage = req.DefaultContentLanguage
		config.Paginate = req.Paginate
		config.Limit = req.Limit
		config.Params.Author = req.Author
		config.Params.Favicon = req.Favicon
		config.Params.Logo = req.Logo
		config.Params.DarkLogo = req.DarkLogo
		config.Params.Description = req.Description
		config.Params.DateFormat = req.DateFormat
		config.Params.BlogGroupBy = req.BlogGroupBy
		config.Params.LatestPostsCount = req.LatestPostsCount
		if req.ShowAllPostsOnHomePage > 0 {
			config.Params.ShowAllPostsOnHomePage = true
		} else {
			config.Params.ShowAllPostsOnHomePage = false
		}
		if req.Article_toc > 0 {
			config.Params.Article.Toc = true
		} else {
			config.Params.Article.Toc = false
		}
		config.Params.About.Title = req.About_title
		config.Params.Footer.Since = req.Footer_since
		config.Params.Footer.CustomText = req.Footer_customText

		data, err := yaml.Marshal(config)
		if err != nil {
			return err
		}
		err = os.WriteFile(filePath, data, 0777)
		return err
	}
}

func (blogService *BlogService) UploadFile(file *multipart.FileHeader) (string, string, error) {
	workDir, _ := os.Getwd()
	// 读取文件后缀
	ext := path.Ext(file.Filename)
	// log.Println("图片后缀：", ext)

	if ext == ".ico" || ext == ".png" || ext == ".jpg" {
		// 拼接新文件名
		filename := file.Filename

		// 拼接路径和文件名
		filePath := workDir + "/../../" + global.GnConfig.System.BlogDir + "/static/images/" + filename
		// log.Println("filePath=", filePath)
		// isFile, err := utils.IsFileExist(filePath)
		// // log.Println("isFile=", isFile, err)
		// if isFile {
		// 	os.Remove(filePath)
		// }
		// if err != nil {
		// 	global.GnLog.Error("function file.Open() Filed", zap.Any("err", err.Error()))
		// 	return "", "", errors.New("function file.Open() Filed, err:" + err.Error())
		// }

		f, openError := file.Open() // 读取文件
		if openError != nil {
			global.GnLog.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
			return "", "", errors.New("function file.Open() Filed, err:" + openError.Error())
		}
		defer f.Close() // 创建文件 defer 关闭

		out, createErr := os.Create(filePath)
		if createErr != nil {
			global.GnLog.Error("function os.Create() Filed", zap.Any("err", createErr.Error()))

			return "", "", errors.New("function os.Create() Filed, err:" + createErr.Error())
		}
		defer out.Close() // 创建文件 defer 关闭

		_, copyErr := io.Copy(out, f) // 传输（拷贝）文件
		if copyErr != nil {
			global.GnLog.Error("function io.Copy() Filed", zap.Any("err", copyErr.Error()))
			return "", "", errors.New("function io.Copy() Filed, err:" + copyErr.Error())
		}

		return "images/" + filename, filename, nil

	} else {
		return "", "", errors.New("只允许上传png图片")
	}
}
